<?php
namespace app\admin\service;

use app\common\model\ModuleLogModel;
use app\common\model\ModuleModel;
use app\common\model\UserModel;


class ModuleService
{
    private static $model;
    private static $userModel;
    private static $moduleLogModel;

    public function __construct(ModuleModel $moduleModel, UserModel $userModel, ModuleLogModel $moduleLogModel)
    {
        self::$model = $moduleModel;
        self::$userModel = $userModel;
        self::$moduleLogModel = $moduleLogModel;
    }

    /**
     * 模块列表
     * User: zhouyao
     * Date: 2018/12/9
     * Time: 12:52 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['page']) || !isset($params['limit']) || !isset
            ($params['guid'])) {
            return app_fail(9997);
        }
        $where = '';
        if(isset($params['machine_code']) && $params['machine_code'])
        {
            $where['machine_code'] = $params['machine_code'];
        }
        $user = self::$userModel->where(['id'=>$params['guid']])->find();
        if(empty($user) || $user->type != 1)
        {
            return ['data' => [], 'count' => 0];
        }
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }

        $result = self::$model->where($where)->page($params['page'], $params['limit'])
            ->select();
        // 把 user_id 转换为 nickname
        $resultArr = $result->toArray();
        $moduleCodes = array_column($resultArr, 'module_code');
        $userArr = array_column($resultArr, 'user_id');

        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');
        $lastModule = $this->get_last_module($moduleCodes);
        $result->each(function ($item) use ($lastModule, $user) {
            $item->update_time = $item['update_time'] ? date('Y-m-d H:i:s',
                $item['update_time']) : '';
            $item->nickname     = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            if(isset($lastModule[$item->module_code]))
            {
                $item->module_name = $lastModule[$item->module_code]['module_name'] ?
                    $lastModule[$item->module_code]['module_name'] : $item->module_name;
                $item->content = $lastModule[$item->module_code]['content'] ?
                    $lastModule[$item->module_code]['content'] : $item->content;
                $item->module_type = $lastModule[$item->module_code]['module_type'] ?
                    $lastModule[$item->module_code]['module_type'] : $item->module_type;
                $item->remark = $lastModule[$item->module_code]['remark'] ?
                    $lastModule[$item->module_code]['remark'] : $item->remark;
                $item->update_time = $lastModule[$item->module_code]['create_time'] ?
                     date('Y-m-d H:i:s',$lastModule[$item->module_code]['create_time']) : '';
            }
            $item->create_time = $item['create_time'] ? date('Y-m-d H:i:s',
                $item['create_time']) : '';
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * zws
     * 根据模块code获取最新的模块信息
     * @param $module_codes
     * @return array
     */
    public function get_last_module($module_codes)
    {
        if(empty($module_codes))
        {
            return [];
        }
        $module_codes_str = "'".implode("','", $module_codes)."'";
        $where = " module_code in ($module_codes_str)";
        $sql = "select a.* from (select * from module_log where $where order by id desc) a GROUP BY a
.module_code";
        $data = [];
        $result = self::$moduleLogModel->query($sql);
        if($result)
        {
            foreach ($result as $v)
            {
                $v['module_id'] = $v['module_code'];
                $data[$v['module_code']] = $v;
            }
        }
        return $data;
    }


    /**
     * zws
     * 删除模块信息
     * @param $params
     * @return bool|void
     */

    public function delete($params)
    {
        if (empty($params) || !isset($params['id'])) {
            return app_fail(9997);
        }

        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        if ($user->type != 1) {
            return app_fail(1000);
        }
        try {
            self::$model->where('id', '=', $params['id'])->delete();
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

}